<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>每日项目工时统计</title>
    <link rel="stylesheet" href="/plugins/layui/css/layui.css" media="all">
    <link rel="stylesheet" type="text/css" href="/build/css/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/css/my-style.css">
</head>
<style>
    .laydate-btns-clear {
        display: none !important;
    }

    .btn-no {
        display: none;
    }
</style>
<body>
<div class="kit-doc">
    <div style="display: none">
        <input th:each="project : ${projectList}" th:value="${project.getId()}"></input>
    </div>
    <!--表格搜索框组-->
    <div class="layui-form-item layui-formgroup layui-tab-card">

        <!-- 下拉框-->
        <div class="layui-inline">
            <form class="layui-form " action="">

                <label class="layui-form-label">项目：</label>
                <div class="layui-input-inline">
                    <select name="interest" id="searchProject" lay-verify="required" lay-search="">
                        <option value=""></option>
                        <option value="" th:each="project : ${projectList}" th:value="${project.getId()}"
                                th:text="${project.getProjectName()}"></option>
                    </select>
                </div>
                <!-- 时间 -->
                <label class="layui-form-label">请选择时间：</label>
                <div class="layui-inline">
                    <input type="hidden" id="mon">
                    <input type="hidden" id="sun">
                    <div class="layui-input-inline">
                        <input class="layui-input" id="test6" placeholder=" 时间段 " type="text">
                    </div>
                </div>
            </form>
        </div>

        <!-- 按钮 -->
        <button class="layui-btn layui-btn-sm" id="search">统计</button>
        <button class="layui-btn layui-btn-sm " id="toLine">折线视图</button>
        <button class="layui-btn layui-btn-sm layui-hide" id="toTable">表格视图</button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="preWeekBtn">
            <i class="fa fa-reply margin-r3"></i>上一周
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="thisWeekBtn">
            <i class="fa fa-search margin-r3"></i>本周
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="nextWeekBtn">
            <i class="fa fa-share margin-r3"></i>下一周
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="preMonthBtn">
            <i class="fa fa-reply margin-r3"></i>上一月
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="thisMonthBtn">
            <i class="fa fa-search margin-r3"></i>本月
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="nextMonthBtn">
            <i class="fa fa-share margin-r3"></i>下一月
        </button>

    </div>
    <div class="layui-card layui-card-body" id="tableDiv">
        <table class="layui-table xuhao-table" id="table-context" lay-filter="test"></table>
    </div>
    <div class="layui-card layui-card-body " style="center: center" id="lineDiv">
        <div class="layui-table xuhao-table " id="line" lay-filter="test"></div>
    </div>

    <script type="text/html" id="toolbarDemo1">
        <div class="layui-btn-container">
            <button class="layui-btn  icon-export" lay-event="exports"> 导出</button>
        </div>
    </script>

</div>
<!-- .js-->
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script src="/plugins/layui/layui.js"></script>
<script src="/js/workhour.js"></script>
<script src="/js/ry-ui.js"></script>
<script type="text/javascript" src="/plugins/echarts/echarts.min.js"></script>
<script>
    var projectToName = function (projectId) {
        return layui.$("#searchProject option[value=" + projectId + "]").text();
    };
</script>
<script type="text/html" id="projectTpl">
    {{ projectToName(d.projectId) }}
</script>

<script>
    var now = new Date();
    // 获取周一和周末
    var start = getTime(0, now);
    var end = getTime(-6, now);
    $("#mon").val(start);
    $("#sun").val(end);
    $("#test6").val(start + ' - ' + end);
</script>
<script>
    function getMonthStartAndEnd(n, sYear, sMonth) {
        //起止日期数组
        let startStop = new Array();
        var monthStartDate;
        var monthEndDate;
        if (n === 0) {
            var now = new Date(); //当前日期
            var nowMonth = now.getMonth(); //当前月
            var nowYear = now.getFullYear(); //当前年
            //本月的开始时间
            monthStartDate = new Date(nowYear, nowMonth, 1);
            monthEndDate = new Date(nowYear, nowMonth + 1, 0);
        } else {
            monthStartDate = new Date(sYear, sMonth + n, 1);
            monthEndDate = new Date(sYear, sMonth + 1 + n, 0);
        }
        startStop.push(dateToStr(monthStartDate))
        startStop.push(dateToStr(monthEndDate))
        return startStop;
    }
</script>

<script>
    //定义一个固定表头(导出用)
    const excelCol = ['项目名称', '合计登记工时']
    //定义一个固定表头
    const col = [
        {field: 'project_name', title: '项目名称', minWidth: 200, fixed: true, align: 'center'},
        {field: 'all', title: '合计登记工时', minWidth: 180, fixed: true, align: 'center'},
    ]
    // 定义一个可变表头
    let cols = []
    // 定义导出时的表头
    let excelCols = []
    // 定义数据表格数据
    let tableData = []
    //定义导出数据
    let exportsData

    let keys = []
    // y轴数据
    let yData = []
    //
    let flag = document.querySelectorAll('input')[0].defaultValue

    // 请求后台数据
    function getData() {
        let startToEnd = $("#test6").val().split(" - ");
        $.ajax({
            type: "post",
            url: '/statistics/project/dailyProject',
            data: {
                startDate: startToEnd[0],
                endDate: startToEnd[1],
                projectId: $("#searchProject").val()
            },
            cache: false,
            async: false,
            dataType: "json",
            success: function (data) {
                tableData = data;
                cols = [];
                excelCols = [];
                // 组装表头
                cols = cols.concat(col)
                excelCols = excelCols.concat(excelCol)

                if (tableData.length > 0) {
                    keys = Object.keys(tableData[0]);
                    // 过滤掉 all 和 project_name
                    keys = keys.filter(item => item !== 'all').filter(item => item !== 'project_name')
                    //按照日期从小到大排序
                    keys.sort(function (a, b) {
                        return Date.parse(a.replace(/-/g, "/")) - Date.parse(b.replace(/-/g, "/"));
                    })
                    // 动态扩充表头
                    keys.forEach(item => {
                        cols.push({field: item, title: item, minWidth: 180, align: 'center'})
                        excelCols.push(item.replace(/-/g, "/"))
                    })
                }
            },
            error: function () {
                alert("请求失败！");
            }
        });
    }

    // 设置折线图
    function getLine() {
        $("#line").css("height", ($("#line").width() * 0.4) + 'px')
        // $("#line").css("witdh", $("#lineDiv").width()  + 'px')
        let startToEnd = $("#test6").val().split(" - ");
        $.ajax({
            type: "post",
            url: '/statistics/project/dailyProject',
            data: {
                startDate: startToEnd[0],
                endDate: startToEnd[1],
                projectId: $("#searchProject").val() == '' ? flag : $("#searchProject").val()
            },
            cache: false,
            async: false,
            dataType: "json",
            success: function (data) {
                keys = []
                yData = []
                if (data.length > 0) {
                    keys = Object.keys(data[0]);
                    // 过滤掉 all 和 project_name
                    keys = keys.filter(item => item !== 'all').filter(item => item !== 'project_name')
                    //按照日期从小到大排序
                    keys.sort(function (a, b) {
                        return Date.parse(a.replace(/-/g, "/")) - Date.parse(b.replace(/-/g, "/"));
                    })
                    // 动态扩充表头
                    keys.forEach(item => {
                        yData.push(data[0][item])
                    })

                }
                let line = echarts.init(document.getElementById('line'));
                var lineOptions = {
                    grid: {
                        left: 70,
                        bottom: 50,
                        right: 70
                    },
                    "tooltip": {
                        "trigger": "axis",
                        axisPointer: {
                            type: 'none'
                        },
                        position: 'inside',

                    },

                    "color": ["#216EDD", "#09DFC0"],
                    "calculable": true,
                    "xAxis": [
                        {
                            name: "时间",
                            nameTextStyle: {
                                color: '#9CA0A6',
                                padding: [20, 0, 0, 0]
                            },
                            nameLocation: 'center',
                            "type": "category",
                            "data": keys,
                            "splitLine": { //x轴内部线条样式
                                "show": false,
                                "lineStyle": {
                                    "type": "solid"
                                }
                            },
                            "axisLine": { //x轴颜色
                                "lineStyle": {
                                    "color": "#000000",
                                    "width": "1",

                                },
                                onZero: false    //-----------设置x轴与y轴最小值对齐
                            },
                            "axisLabel": { //x轴文字样式
                                "textStyle": {
                                    "color": "#7F7F7F"
                                },
                                // margin: 18
                            },
                            axisTick: { //柱子与刻度对齐
                                alignWithLabel: true
                            }
                        }
                    ],
                    "yAxis": [
                        {
                            name: '工时 (单位 / 小时）',
                            nameTextStyle: {
                                color: '#9CA0A6',
                                padding: [0, 0, 20, 0]
                            },
                            nameLocation: 'center',
                            nameRotate: '90',
                            "type": "value",
                            "splitLine": { //y轴内部线条样式
                                "show": true,
                                "lineStyle": {
                                    "type": "solid"
                                }
                            },
                            "axisTick": { //y轴刻度线
                                "show": false
                            },
                            "axisLabel": { //x轴文字样式
                                "textStyle": {
                                    "color": "#7F7F7F"
                                },
                                margin: 12
                            },
                            "axisLine": { //y轴
                                "show": false,
                                "lineStyle": {
                                    "color": "#000000",
                                    "width": "1"
                                }
                            },
                            scale: true
                        }
                    ],
                    "series": [
                        {
                            "name": "工时",
                            "type": "line",
                            "data": yData,
                            yAxisIndex: 0, //具体使用左右Y轴 0左1右
                            symbol: "true" //拐点
                        }
                    ]
                }
                line.setOption(lineOptions);
            },
            error: function () {
                alert("请求失败！");
            }
        });
    }

    // 默认统计本周
    getData()
    getLine()

    layui.config({
        base: '/plugins/layui_exts/',
    }).extend({
        excel: 'excel',
    }).use(['table', 'excel', 'jquery','form'], function () {
        var table = layui.table;
        var excel = layui.excel;
        var $ = layui.$;
        var form = layui.form;
        var dailyTable = table.render({
            elem: '#table-context'
            , title: '项目每日统计'
            , toolbar: '#toolbarDemo1'
            , defaultToolbar: []
            , height: 'full-190'
            , loading: true
            , page: true
            , limit: 20
            , limits: [10, 20, 30, 40, 50]
            , cols: [cols]
            , data: tableData
            , done: function (res, curr, count) {
                exportsData = []
                exportsData = res.data
            }
        });

        table.on('toolbar(test)', function (obj) {
                switch (obj.event) {
                    case 'exports':
                        //导出的数据
                        let exportData = []
                        let rowData = []
                        let tableData = table.cache["table-context"];
                        exportData.push(excelCols)
                        for (var i = 0; i < tableData.length; i++) {
                            rowData = []
                            rowData.push(tableData[i].project_name)
                            rowData.push(tableData[i].all)
                            keys.forEach(item => {
                                rowData.push(tableData[i][item])
                            })
                            exportData.push(rowData)
                        }
                        //  配置 列宽 设置默认列宽80失效
                        var colConf = excel.makeColConfig({
                            'A': 170, 'B': 100, 'C': 80,'D': 80,'E': 80,'F': 80,'G': 80,'H': 80,'I': 80,'J': 80,'K': 80,'L': 80,'M': 80,
                            'N': 80,'O': 80,'P': 80,'Q': 80,'R': 80,'S': 80,'T': 80,'U': 80,'V': 80,'W': 80,'X': 80,'Y': 80,'Z': 80,
                            'AA': 80, 'AB':80, 'AC':80, 'AD':80, 'AE':80, 'AF':80, 'AG':80
                        }, 80)
                        //  第1行行高25，默认20（失效）
                        var rowConf = excel.makeRowConfig({
                            1: 25, 2: 20, 3: 20, 4: 20, 5: 20, 6: 20, 7: 20, 8: 20, 9: 20, 10: 20, 11: 20, 12: 20,
                            21: 25, 22: 20, 23: 20, 24: 20, 25: 20, 26: 20, 27: 20, 28: 20, 29: 20, 30: 20, 31: 20, 32: 20,
                        }, 20)
                        /*设置表格数据居中*/
                        excel.setExportCellStyle(exportData, '', {
                            s: {
                                alignment: {
                                    horizontal: 'center'
                                }
                            }
                        })


                        //设置表格名称
                        excel.exportExcel({
                                sheet1: exportData
                            }, $("#test6").val()+'项目每日查看.xlsx', 'xlsx',{
                                extend: {
                                    '!cols': colConf
                                    , '!rows': rowConf
                                }
                            }


                        );

                        break;
                }

            }
        );

        function reloadData() {
            var startToEnd = $("#test6").val().split(" - ");
            dailyTable.reload({
                elem: '#table-context'
                , height: 'full-150'
                , loading: true
                , cols: [cols]
                , data: tableData
                , done: function (res, curr, count) {
                    exportsData = []
                    exportsData = res.data
                }
            });
        }

        // 搜索
        $("#search").click(function () {
            getData()
            getLine()
            reloadData()
        });

        // 去到折线视图
        $("#toLine").click(function () {
            if($('#searchProject').val()===''){
                // 默认选择 开始时间最近的项目
                $('#searchProject').val(flag);
                // 更新全部
                layui.form.render();
            }
            $("#toLine").addClass("layui-hide")
            $("#toTable").removeClass("layui-hide")

            $("#tableDiv").addClass("layui-hide")
            $("#lineDiv").removeClass("layui-hide")
        });
        //去到表格视图
        $("#toTable").click(function () {
            $("#toTable").addClass("layui-hide")
            $("#toLine").removeClass("layui-hide")

            $("#tableDiv").removeClass("layui-hide")
            $("#lineDiv").addClass("layui-hide")
        });


        // 上一周
        $("#preWeekBtn").click(function () {
            var monDate = $("#mon").val();
            var preMon = dateToStr(addDate(monDate, -7));
            var preSun = dateToStr(addDate(monDate, -1));
            $("#mon").val(preMon);
            $("#sun").val(preSun);
            $("#test6").val(preMon + ' - ' + preSun);
            getData()
            getLine()
            reloadData()
        });

        // 下一周
        $("#nextWeekBtn").click(function () {
            var monDate = $("#mon").val();
            var nextMon = dateToStr(addDate(monDate, 7));
            var nextSun = dateToStr(addDate(monDate, 13));
            $("#mon").val(nextMon);
            $("#sun").val(nextSun);
            $("#test6").val(nextMon + ' - ' + nextSun);
            getData()
            getLine()
            reloadData()
        });

        // 本周一周
        $("#thisWeekBtn").click(function () {
            var now = new Date();
            // 获取周一和周末
            var start = getTime(0, now);
            var end = getTime(-6, now);
            $("#mon").val(start);
            $("#sun").val(end);
            $("#test6").val(start + ' - ' + end);
            getData()
            getLine()
            reloadData()
        });

        // 上个月
        $("#preMonthBtn").click(function () {
            var dateArr = $("#test6").val().split("-");
            var monthSD = getMonthStartAndEnd(-1, Number(dateArr[0]), Number(dateArr[1]) - 1);
            $("#test6").val(monthSD[0] + ' - ' + monthSD[1]);
            getData($("#searchProject").val())
            getLine()
            reloadData()
        });
        // 本月
        $("#thisMonthBtn").click(function () {
            var dateArr = $("#test6").val().split("-");
            var monthSD = getMonthStartAndEnd(0, Number(dateArr[0]), Number(dateArr[1]) - 1);
            $("#test6").val(monthSD[0] + ' - ' + monthSD[1]);
            getData()
            getLine()
            reloadData()
        });
        // 下个月
        $("#nextMonthBtn").click(function () {
            var dateArr = $("#test6").val().split("-");
            var monthSD = getMonthStartAndEnd(1, Number(dateArr[0]), Number(dateArr[1]) - 1);
            $("#test6").val(monthSD[0] + ' - ' + monthSD[1]);
            getData()
            getLine()
            reloadData()
        });


    });

    $("#lineDiv").addClass("layui-hide")
</script>

<script>
</script>
</body>
</html>